<template>
  <div class="outsourcing-container">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-title">
        <el-icon><Document /></el-icon>
        <span>外协入库管理</span>
      </div>
      <div class="header-actions">
        <el-button type="primary" @click="OpenAdd" class="add-button">
          <el-icon><Plus /></el-icon>新增入库单
        </el-button>
      </div>
    </div>

    <!-- 搜索区域 -->
    <div class="search-card">
      <el-form :inline="true" :model="sreach" class="search-form">
        <el-form-item label="入库单编号">
          <el-input
            v-model="sreach.stockroomCode"
            placeholder="请输入入库单编号"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Document /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="入库单名称">
          <el-input
            v-model="sreach.stockroomName"
            placeholder="请输入入库单名称"
            clearable
            class="search-input"
          >
            <template #prefix>
              <el-icon><Edit /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="供应商">
          <el-select
            v-model="sreach.supplierName"
            placeholder="请选择供应商"
            clearable
            class="search-select"
          >
            <el-option label="供应商A" value="供应商A" />
            <el-option label="供应商B" value="供应商B" />
            <el-option label="供应商C" value="供应商C" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch" :loading="loading">
            <el-icon><Search /></el-icon>查询
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-card">
      <el-table
        v-loading="loading"
        :data="tableData"
        border
        stripe
        style="width: 100%"
        highlight-current-row
        :header-cell-style="{
          background: '#f5f7fa',
          color: '#606266',
          height: '50px',
          fontWeight: '600'
        }"
      >
        <el-table-column  prop="stockroomCode" label="入库单编号" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <span class="code-column">{{ scope.row.stockroomCode }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="stockroomName" label="入库单名称" min-width="130" show-overflow-tooltip />
        <el-table-column prop="stockroomData" label="入库日期" width="120">
          <template #default="scope">
            <span class="date-column">{{ formatDate(scope.row.stockroomData) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="outsourcing" label="外协工单" min-width="120" show-overflow-tooltip>
          <template #default="scope">
            <el-tag size="small" type="info">{{ scope.row.outsourcing }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="procurementNum" label="采购数量" width="100" align="right">
          <template #default="scope">
            <span class="number-column">{{ scope.row.procurementNum }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="supplierName" label="供应商" min-width="120" show-overflow-tooltip />
        <el-table-column prop="stockWareroom" label="仓库" min-width="120" show-overflow-tooltip />
        <el-table-column prop="descs" label="备注" min-width="130" show-overflow-tooltip>
          <template #default="scope">
            <el-tooltip
              v-if="scope.row.descs"
              :content="scope.row.descs"
              placement="top"
              effect="light"
            >
              <span class="remarks">{{ scope.row.descs }}</span>
            </el-tooltip>
            <span v-else class="no-remarks">暂无备注</span>
          </template>
        </el-table-column>
        <el-table-column prop="isDocument" label="单据状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="scope.row.isDocument === 0 ? 'info' : scope.row.isDocument === 1 ? 'warning' : 'success'">
              {{ scope.row.isDocument === 0 ? '草稿' : scope.row.isDocument === 1 ? '待审核' : '已审核' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="290" fixed="right" align="center">
          <template #default="scope">
            <div class="operation-buttons">
              <el-button
                v-if="scope.row.isDocument === 1"
                type="success"
                link
                @click="handleExecute(scope.row)"
              >
                <el-icon><VideoPlay /></el-icon>执行入库
              </el-button>
              <el-divider direction="vertical" />
              <el-button
                type="primary"
                link
                @click="handleEdit(scope.row)"
              >
                <el-icon><Edit /></el-icon>编辑
              </el-button>
              <el-divider direction="vertical" />
              <el-button type="danger" link @click="handleDelete(scope.row)">
                <el-icon><Delete /></el-icon>删除
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页器 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="page.pageIndex"
          v-model:page-size="page.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="page.totalCount"
        />
      </div>
    </div>

    <!-- 新增对话框 -->
    <el-dialog
      v-model="addDialogVisible"
      title="新增外协入库单"
      width="850px"
      destroy-on-close
      :close-on-click-modal="false"
    >
      <el-form
        ref="addFormRef"
        :model="addForm"
        :rules="rules"
        label-width="100px"
        class="dialog-form"
      >
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入库单编号" prop="stockroomCode">
                <div class="code-input-group">
                  <el-input
                    v-model="addForm.stockroomCode"
                    :disabled="isAutoGenerate"
                    placeholder="请输入入库单编号"
                    :maxlength="20"
                    show-word-limit
                  />
                  <el-switch
                    v-model="isAutoGenerate"
                    class="ml-2"
                    inline-prompt
                    :active-text="'自动'"
                    :inactive-text="'手动'"
                    @change="handleAutoGenerateChange"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库单名称" prop="stockroomName">
                <el-input
                  v-model="addForm.stockroomName"
                  placeholder="请输入入库单名称"
                  :maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入库日期" prop="stockroomData">
                <el-date-picker
                  v-model="addForm.stockroomData"
                  type="date"
                  placeholder="请选择入库日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="外协工单" prop="outsourcing">
                <el-input
                  v-model="addForm.outsourcing"
                  placeholder="请输入外协工单号"
                  :maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <div class="section-title">采购信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="采购数量" prop="procurementNum">
                <el-input-number
                  v-model="addForm.procurementNum"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  placeholder="请输入采购数量"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierName">
                <el-select
                  v-model="addForm.supplierName"
                  placeholder="请选择供应商"
                  style="width: 100%"
                >
                  <el-option label="供应商A" value="供应商A" />
                  <el-option label="供应商B" value="供应商B" />
                  <el-option label="供应商C" value="供应商B" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="仓库" prop="stockWareroom">
                <el-select
                  v-model="addForm.stockWareroom"
                  placeholder="请选择仓库"
                  style="width: 100%"
                >
                  <el-option label="仓库A" value="仓库A" />
                  <el-option label="仓库B" value="仓库B" />
                  <el-option label="仓库C" value="仓库C" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单据状态" prop="isDocument">
                <el-select
                  v-model="addForm.isDocument"
                  placeholder="请选择单据状态"
                  style="width: 100%"
                  disabled
                >
                  <el-option label="草稿" :value="0" />
                  <el-option label="待审核" :value="1" />
                  <el-option label="已审核" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <div class="section-title">其他信息</div>
          <el-form-item label="备注" prop="descs">
            <el-input
              type="textarea"
              v-model="addForm.descs"
              placeholder="请输入备注信息"
              :rows="3"
              :maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleAdd" :loading="saveLoading">
            确认新增
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      title="编辑外协入库单"
      width="80%"
      :close-on-click-modal="false"
    >
      <el-form :model="form" label-width="120px">
        <div class="form-section">
          <div class="section-title">基本信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入库单编号" prop="stockroomCode">
                <el-input
                  v-model="form.stockroomCode"
                  placeholder="请输入入库单编号"
                  :maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="入库单名称" prop="stockroomName">
                <el-input
                  v-model="form.stockroomName"
                  placeholder="请输入入库单名称"
                  :maxlength="50"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="入库日期" prop="stockroomData">
                <el-date-picker
                  v-model="form.stockroomData"
                  type="date"
                  placeholder="请选择入库日期"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="外协工单" prop="outsourcing">
                <el-input
                  v-model="form.outsourcing"
                  placeholder="请输入外协工单号"
                  :maxlength="20"
                  show-word-limit
                />
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <div class="section-title">采购信息</div>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="采购数量" prop="procurementNum">
                <el-input-number
                  v-model="form.procurementNum"
                  :min="0"
                  :precision="0"
                  style="width: 100%"
                  placeholder="请输入采购数量"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="供应商" prop="supplierName">
                <el-select
                  v-model="form.supplierName"
                  placeholder="请选择供应商"
                  style="width: 100%"
                >
                  <el-option label="供应商A" value="供应商A" />
                  <el-option label="供应商B" value="供应商B" />
                  <el-option label="供应商C" value="供应商B" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="仓库" prop="stockWareroom">
                <el-select
                  v-model="form.stockWareroom"
                  placeholder="请选择仓库"
                  style="width: 100%"
                >
                  <el-option label="仓库A" value="仓库A" />
                  <el-option label="仓库B" value="仓库B" />
                  <el-option label="仓库C" value="仓库C" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="单据状态" prop="isDocument">
                <el-select
                  v-model="form.isDocument"
                  placeholder="请选择单据状态"
                  style="width: 100%"
                  disabled
                >
                  <el-option label="草稿" :value="0" />
                  <el-option label="待审核" :value="1" />
                  <el-option label="已审核" :value="2" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
        </div>

        <div class="form-section">
          <div class="section-title">其他信息</div>
          <el-form-item label="备注" prop="descs">
            <el-input
              type="textarea"
              v-model="form.descs"
              placeholder="请输入备注信息"
              :rows="3"
              :maxlength="200"
              show-word-limit
            />
          </el-form-item>
        </div>

        <!-- 物料信息部分 -->
        <div class="material-divider">
          <span class="divider-text">物料信息</span>
        </div>

        <el-table 
          :data="tableData1" 
          border 
          stripe
          highlight-current-row
          :max-height="500"
          style="width: 100%"
          @current-change="handleCurrentChange"
        >
          <el-table-column width="55" fixed="left">
            <template #default="scope">
              <el-radio 
                v-model="selectedRow" 
                :label="scope.row" 
                @change="handleRadioChange(scope.row.materialCode)"
              >
                &nbsp;
              </el-radio>
            </template>
          </el-table-column>
          <el-table-column type="index" label="序号" width="60" fixed="left" />
          <el-table-column prop="materialCode" label="物料编码" min-width="120" fixed="left">
            <template #default="scope">
              <el-tooltip :content="scope.row.materialCode" placement="top" :show-after="1000">
                <span>{{ scope.row.materialCode }}</span>
              </el-tooltip>
            </template>
          </el-table-column>
          <el-table-column prop="materialName" label="物料名称" min-width="150" show-overflow-tooltip>
            <template #default="scope">
              <el-link type="primary" @click="showMaterialDetail(scope.row)">
                {{ scope.row.materialName }}
              </el-link>
            </template>
          </el-table-column>
          <el-table-column prop="specification" label="规格型号" min-width="120" show-overflow-tooltip />
          <el-table-column prop="flats" label="单位" width="80" align="center" />
          <el-table-column prop="flatsMaterial" label="物料产品分类" min-width="120" show-overflow-tooltip />
          <el-table-column prop="safetyStock" label="安全库存" width="100" align="right">
            <template #default="scope">
              <span :class="{ 'text-danger': isLowStock(scope.row) }">
                {{ scope.row.safetyStock }}
              </span>
            </template>
          </el-table-column>
          <el-table-column prop="descs" label="备注" min-width="150" show-overflow-tooltip />
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleUpdate" :loading="saveLoading">
            保存
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance } from 'element-plus'
import { 
  Search, 
  Refresh, 
  Plus, 
  Edit, 
  Delete, 
  Document,
  Setting,
  InfoFilled,
  VideoPlay,
  View
} from '@element-plus/icons-vue'
import axios from 'axios'
import { useRouter, useRoute } from 'vue-router'
import dayjs from 'dayjs'
import http from '@/api/http'

const router = useRouter()
const route = useRoute()
const addFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()

// 加载状态
const loading = ref(false)
const saveLoading = ref(false)

// 查询条件
const sreach = reactive({
  stockroomCode: '',
  stockroomName: '',
  supplierName: ''
})

// 分页条件
const page = reactive({
  pageIndex: 1,
  pageSize: 10,
  totalCount: 0,
  totalPage: 0
})

// 表单校验规则
const rules = {
  stockroomCode: [
    { required: true, message: '请输入入库单编号', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 20 个字符', trigger: 'blur' }
  ],
  stockroomName: [
    { required: true, message: '请输入入库单名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  stockroomData: [
    { required: true, message: '请选择入库日期', trigger: 'change' }
  ],
  outsourcing: [
    { required: true, message: '请输入外协工单号', trigger: 'blur' }
  ],
  procurementNum: [
    { required: true, message: '请输入采购数量', trigger: 'blur' },
    { type: 'number', min: 0, message: '采购数量必须大于等于0', trigger: 'blur' }
  ],
  supplierName: [
    { required: true, message: '请选择供应商', trigger: 'change' }
  ],
  stockWareroom: [
    { required: true, message: '请选择仓库', trigger: 'change' }
  ],
}

// 新增表单数据
const addForm = reactive({
  stockroomCode: '',
  stockroomName: '',
  stockroomData: '',
  outsourcing: '',
  isDocument: 0,
  procurementNum: 0,
  supplierName: '',
  stockWareroom: '',
  descs: '',
  materialCode: ''
})

// 表单数据
const form = reactive({
  id: 0,
  stockroomCode: '',
  stockroomName: '',
  stockroomData: '',
  outsourcing: '',
  procurementNum: 0,
  supplierName: '',
  stockWareroom: '',
  isDocument: 0,
  descs: '',
  materialCode: '',
})

// 表格数据
const tableData = ref([])

// 物料表格数据
const tableData1 = ref<MaterialItem[]>([])

// 对话框显示状态
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)

// 选中的行数据
const selectedRow = ref<MaterialItem | null>(null)

// 是否自动生成编号
const isAutoGenerate = ref(true)

interface MaterialItem {
  materialCode: string
  materialName: string
  specification: string
  flats: string
  flatsMaterial: string
  safetyStock: number
  descs: string
}

// 获取数据列表
const funShow = async () => {
  try {
    loading.value = true
    const res = await axios.get('http://localhost:9991/api/WarehouseManagement/GetOutSourcingWareHousingList', {
      params: {
        pageIndex: page.pageIndex,
        pageSize: page.pageSize,
        stockroomCode: sreach.stockroomCode,
        stockroomName: sreach.stockroomName,
        supplierName: sreach.supplierName
      }
    })
    tableData.value = res.data.data
    page.totalCount = res.data.data.totalCount
    page.totalPage = res.data.data.totalPages
  } catch (error: any) {
    ElMessage.error('获取数据失败：' + error.message)
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  page.pageIndex = 1
  funShow()
}

// 重置搜索
const resetSearch = () => {
  sreach.stockroomCode = ''
  sreach.stockroomName = ''
  sreach.supplierName = ''
  funShow()
}

// 打开新增对话框
const OpenAdd = () => {
  resetForm()
  if (isAutoGenerate.value) {
    // 生成编号：RK + 年月日 + 4位随机数
    const date = new Date()
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
    addForm.stockroomCode = `RK${year}${month}${day}${random}`
  }
  addDialogVisible.value = true
}

// 处理编辑
const handleEdit = async (row: any) => {
  // 更新表单数据
  Object.assign(form, {
    id: row.id,
    orderNo: row.orderNo,
    stockroomCode: row.stockroomCode,
    stockroomName: row.stockroomName,
    stockroomData: row.stockroomData,
    outsourcing: row.outsourcing,
    procurementNum: row.procurementNum,
    supplierName: row.supplierName,
    stockWareroom: row.stockWareroom,
    isDocument: row.isDocument,
    descs: row.descs,
    materialCode: row.materialCode
  })

  // 获取物料列表数据
  await getMaterialList()
  
  // 如果有物料编码，设置选中状态
  if (row.materialCode) {
    const selectedMaterial = tableData1.value.find(
      (item: MaterialItem) => item.materialCode === row.materialCode
    )
    selectedRow.value = selectedMaterial || null
  } else {
    selectedRow.value = null
  }
  
  // 打开编辑对话框
  editDialogVisible.value = true
}

// 获取物料列表数据
const getMaterialList = async () => {
  try {
    const res = await axios.get('http://localhost:9991/api/MaterialProduct/GetMaterialProductList')

    tableData1.value = res.data
  } catch (error) {
    ElMessage.error('获取物料列表失败')
  }
}

// 处理单选按钮变化
const handleRadioChange = (materialCode: string) => {
  form.materialCode = materialCode
  ElMessage.success('已选中该物料')
}

// 处理当前行变化
const handleCurrentChange = (currentRow: any) => {
  if (currentRow) {
    selectedRow.value = currentRow
    handleRadioChange(currentRow.materialCode)
  }
}

// 删除
const handleDelete = (row: any) => {
  ElMessageBox.confirm('确认删除该入库单?', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(async () => {
    try {
      loading.value = true
      await http.post('api/WarehouseManagement/DeleteOutSourcingWareHousing', row)
      ElMessage.success('删除成功')
      funShow()
    } catch (error: any) {
      ElMessage.error('删除失败：' + error.message)
    } finally {
      loading.value = false
    }
  })
}

// 新增保存
const handleAdd = async () => {
  if (!addFormRef.value) return
  
  try {
    await addFormRef.value.validate()
    saveLoading.value = true
    
    const params = {
      ...addForm,
      stockroomData: dayjs(addForm.stockroomData).format('YYYY-MM-DD')
    }
    
    const res = await http.post('api/WarehouseManagement/CreateOutSourcingWareHousing', params)
    
    ElMessage.success('新增成功')
      addDialogVisible.value = false
      funShow()
  } catch (error: any) {
    console.error('新增失败:', error)
    ElMessage.error('新增失败：' + (error.response?.data?.message || error.message))
  } finally {
    saveLoading.value = false
  }
}

// 编辑保存
const handleUpdate = async () => {
  try {
    saveLoading.value = true
    
    if (form.materialCode.length === 0) {
      ElMessage.warning('请选择物料')
      return
    }

    // 更新状态为待审核
    form.isDocument = 1

    // 这里添加您的保存API调用
    await http.post('api/WarehouseManagement/UpdateOutSourcingWareHousing', form)

    ElMessage.success('保存成功')
    editDialogVisible.value = false
    // 刷新列表
    funShow()
  } catch (error) {
    console.error('保存失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saveLoading.value = false
  }
}

// 格式化日期
const formatDate = (date: string) => {
  return date ? dayjs(date).format('YYYY-MM-DD') : ''
}

// 监听分页变化
watch(page, () => {
  funShow()
})

// 初始化
onMounted(() => {
  funShow()
})

// 处理物料选择变化
const handleSelectionChange = (selection: any[]) => {
  console.log('选中的物料:', selection)
}

// 显示物料详情
const showMaterialDetail = (row: any) => {
  ElMessageBox.alert(
    `物料详细信息：
    编码：${row.materialCode}
    名称：${row.materialName}
    规格：${row.cpecification}
    单位：${row.flats}
    分类：${row.flatsMaterial}
    安全库存：${row.safetyStock}
    备注：${row.descs}`,
    '物料详情',
    {
      confirmButtonText: '确定'
    }
  )
}

// 判断是否低库存
const isLowStock = (row: any) => {
  // 假设安全库存低于100时显示红色警告
  return Number(row.safetyStock) < 100
}

// 查看物料详情
const handleView = (row: any) => {
  showMaterialDetail(row)
}

// 处理执行入库
const handleExecute = async (row: any) => {
  try {
    await ElMessageBox.confirm('确认要执行入库操作吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 调用执行入库API
    await http.post('api/WarehouseManagement/ExecuteWarehousing', row)
    
    ElMessage.success('执行入库成功')
    // 刷新列表
    funShow()
  } catch (error) {
    console.error('执行入库失败:', error)
    ElMessage.error('执行入库失败')
  }
}

// 处理自动生成开关变化
const handleAutoGenerateChange = (value: boolean) => {
  if (value) {
    // 生成编号：RK + 年月日 + 4位随机数
    const date = new Date()
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    const day = String(date.getDate()).padStart(2, '0')
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
    addForm.stockroomCode = `RK${year}${month}${day}${random}`
    ElMessage.success('已自动生成入库单编号')
  } else {
    addForm.stockroomCode = ''
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(addForm, {
    stockroomCode: '',
    stockroomName: '',
    stockroomData: '',
    outsourcing: '',
    procurementNum: 0,
    supplierName: '',
    stockWareroom: '',
    isDocument: 0,
    descs: '',
    materialCode: ''
  })
  isAutoGenerate.value = true
}

// 生成入库单编号
const generateStockroomCode = () => {
  const date = new Date()
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0')
  return `RK${year}${month}${day}${random}`
}
</script>

<style lang="scss" scoped>
.outsourcing-container {
  padding: 24px;
  background-color: #f5f7fa;
  min-height: calc(100vh - 48px);
}

.page-header {
  margin-bottom: 24px;
  background-color: #fff;
  padding: 16px 24px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-title {
    display: flex;
    align-items: center;
    gap: 8px;
    font-size: 18px;
    font-weight: 600;
    color: #303133;

    .el-icon {
      font-size: 20px;
      color: #409eff;
    }
  }

  .add-button {
    transition: all 0.3s ease;

    &:hover {
      transform: translateY(-2px);
    }
  }
}

.search-card {
  margin-bottom: 24px;
  background-color: #fff;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);

  .search-form {
    display: flex;
    flex-wrap: wrap;
    gap: 16px;

    .el-form-item {
      margin-bottom: 0;
      margin-right: 0;
    }

    .search-input,
    .search-select {
      width: 220px;
    }

    .date-picker {
      width: 360px;
    }
  }
}

.table-card {
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 20px;

  .code-column {
    color: #409eff;
    font-family: Monaco, Menlo, Consolas, monospace;
  }

  .date-column {
    color: #67c23a;
  }

  .number-column {
    color: #409eff;
    font-family: Monaco, Menlo, Consolas, monospace;
    font-weight: 500;
  }

  .remarks {
    color: #606266;
    cursor: pointer;

    &:hover {
      color: #409eff;
    }
  }

  .no-remarks {
    color: #909399;
    font-style: italic;
  }

  .operation-buttons {
    display: flex;
    justify-content: center;
    align-items: center;
    gap: 8px;

    .el-button {
      padding: 4px 8px;
      transition: all 0.3s;

      &:hover {
        transform: translateY(-2px);
      }
    }
  }
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-form {
  .form-section {
    margin-bottom: 24px;
    padding: 16px;
    background-color: #f5f7fa;
    border-radius: 8px;

    &:last-child {
      margin-bottom: 0;
    }

    .section-title {
      margin-bottom: 16px;
      font-size: 16px;
      font-weight: 600;
      color: #303133;
      display: flex;
      align-items: center;
      gap: 8px;

      &::before {
        content: '';
        width: 4px;
        height: 16px;
        background-color: #409eff;
        border-radius: 2px;
      }
    }
  }

  :deep(.el-form-item__label) {
    font-weight: 500;
  }

  :deep(.el-input__wrapper),
  :deep(.el-textarea__wrapper) {
    box-shadow: 0 0 0 1px #dcdfe6 inset;

    &:hover {
      box-shadow: 0 0 0 1px #409eff inset;
    }
  }
}

.dialog-footer {
  padding-top: 16px;
  text-align: right;

  .el-button {
    padding: 8px 20px;
    font-weight: 500;
    transition: all 0.3s;

    &:hover {
      transform: translateY(-2px);
    }
  }
}

.material-divider {
  position: relative;
  text-align: center;
  margin: 20px 0;
  
  &::before {
    content: '';
    position: absolute;
    top: 50%;
    left: 0;
    width: 100%;
    height: 1px;
    background-color: #dcdfe6;
  }
  
  .divider-text {
    position: relative;
    display: inline-block;
    padding: 0 20px;
    background-color: #fff;
    color: #606266;
    font-size: 16px;
    font-weight: 500;
  }
}

.material-table {
  margin-top: 20px;
  
  .table-header {
    margin-bottom: 16px;
    display: flex;
    justify-content: flex-end;
  }
}

.text-danger {
  color: #f56c6c;
  font-weight: bold;
}

:deep(.el-radio) {
  margin-right: 0;
  width: 100%;
  display: flex;
  justify-content: center;
}

:deep(.el-radio__input) {
  margin-right: 0;
}

:deep(.el-radio__label) {
  display: none;
}

.code-input-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.code-input-group .el-input {
  flex: 1;
}

:deep(.el-switch) {
  margin-left: 8px;
}
</style>
